package at.ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class RibbonRandomRuleConfig extends AbstractLoadBalancerRule {

    // 自定义负载均衡策略
    @Override
    public Server choose(Object o) {
        // 获取当前请求的服务提供者的实例
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        List<Server> reachableServers = loadBalancer.getReachableServers();
        Server server = null;
        do {
            int random = ThreadLocalRandom.current().nextInt(reachableServers.size());
            server = reachableServers.get(random);
        } while (!(server.isAlive()));
        return server;
    }
    // 初始化配置
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}